import React, { FC, memo, ReactNode, useEffect, useState } from 'react'
import { FormInstance, Input, Tag, TreeSelect } from 'antd'
import { ActionDesc } from '@/global/constant'
import confirmModal from '@/utils/confirm-modal'
import {
  fetchPageAddOrEditAction,
  fetchPageDeleteAction
} from '@/store/module/main/page-common'
import { fetchParentMenuListAction } from '@/store/module/main/menu-list'
import usePageModal from '@/hooks/use-page-modal'
import PageContent from '@/components/page-content'
import PageModal from '@/components/page-modal'
import VerifyCodeButton from '@/components/verify-code-button'
import menuListContent from './config/menulist-content'
import getMenuListModalAddOrEdit from './config/menulist-modal-add-or-edit'
import usePageContent from '@/hooks/use-page-content'

interface IProps {
  children?: ReactNode
}

const inputWithVerifyCodeStyle = {
  display: 'flex',
  alignItems: 'center'
}

const treeFieldsName = {
  label: 'menuLabel',
  value: 'menuId'
}

const MenuList: FC<IProps> = (props) => {
  // 通用：modal的确定与取消：主要事件，
  const okCb = async (form: FormInstance | undefined) => {
    // 获取当前配置的信息，看一下是属于什么类型的表单描述
    const { desc } = curModalConfig.formProps
    // 获取表单数据
    const values = form?.getFieldsValue()
    if (desc === ActionDesc.SecondAuth) {
      /** 1、当前描述为：二次认证 **/
      toSecondAuth(values)
    } else if (desc === ActionDesc.Add) {
      return dispatch(
        fetchPageAddOrEditAction({
          params: values,
          isAdd: true,
          isNeedEncrypt: false
        })
      )
    } else if (desc === ActionDesc.Edit) {
      const { menuCode, type, ...filterValues } = values
      const params = { ...filterValues, menuId: currentRecord.menuId }
      return dispatch(
        fetchPageAddOrEditAction({
          params,
          isAdd: false,
          isNeedEncrypt: false
        })
      )
    }
  }
  const cancelCb = () => {
    setCurModalConfig({})
  }

  const afterCloseResetStatusCb = () => {
    setCurModalConfig({})
  }

  const { pageModalRef, onModalOk, onModalCancel, getCodeClick } = usePageModal(
    { okCb, cancelCb, afterCloseResetStatusCb }
  )
  const {
    modal: [curModalConfig, setCurModalConfig],
    record: [currentRecord, setCurrentRecord],
    dispatch,
    toSecondAuth,
    handleSecondAuth
  } = usePageContent({ pageModalRef })

  // 上级菜单数据
  const [parentMenuList, setParentMenuList] = useState([])
  // 当前选中的上级菜单
  const [selectedParentId, setSelectedParentId] = useState(-1)
  // 通用：处理“编辑”的回显数据的，只要config一改变，就手动设置初始值
  useEffect(() => {
    if (curModalConfig?.formProps?.desc === ActionDesc.Edit) {
      const { menuLabel, menuCode, name, path, url, type, elIcon, parentId } =
        currentRecord
      const recordObj = {
        menuLabel,
        menuCode,
        name,
        path,
        url,
        type,
        elIcon,
        parentId
      }
      const form = pageModalRef.current?.getFormInstance()
      form?.setFieldsValue(recordObj)
      // 重新设置值，触发组件更新，渲染新组件
      pageModalRef.current?.updateFormView(recordObj)
    }
  }, [curModalConfig])

  // 打开新增或者编辑框之前的回调
  const onOpenAddOrEditModalBefore = (isAdd: boolean) => {
    // 获取上级菜单数据
    dispatch(fetchParentMenuListAction()).then(({ payload }) => {
      // 更新菜单数据状态到树形结构
      setParentMenuList(payload)
      // 获取modal框配置
      const config = getMenuListModalAddOrEdit(isAdd)
      // 更新modal状态
      setCurModalConfig(config)
      pageModalRef.current?.openModal()
    })
  }

  const actionClick = (actionType: any, record?: any) => {
    // 设置当前行数据：如果是批量操作和新增就没有record也要设置，表明是空状态
    setCurrentRecord(record)
    if (actionType === ActionDesc.Delete) {
      /** 删除 **/
      handleSecondAuth(() => {
        confirmModal('是否删除该菜单?').then(() =>
          dispatch(fetchPageDeleteAction(record.menuId))
        )
      })
    } else if (actionType === ActionDesc.Add) {
      onOpenAddOrEditModalBefore(true)
    } else if (actionType === ActionDesc.Edit) {
      onOpenAddOrEditModalBefore(false)
    }
  }

  const onTreeChange = (newValue: number) => {
    setSelectedParentId(newValue)
  }

  // 通用：自定义表格内容--渲染自定义的表单项
  const renderTableCpn = (
    text: string | number,
    record: any,
    customkey: string
  ) => {
    const typeMap: any = {
      0: { color: 'success', label: '目录' },
      1: { color: 'processing', label: '菜单' },
      2: { color: 'error', label: '按钮' }
    }
    switch (customkey) {
      case 'type':
        return <Tag color={typeMap[text]?.color}>{typeMap[text]?.label}</Tag>
      default:
        return <span>{text}</span>
    }
  }
  return (
    <>
      <PageContent config={menuListContent} actionClick={actionClick}>
        {renderTableCpn}
      </PageContent>
      <PageModal
        ref={pageModalRef}
        modalConfig={curModalConfig}
        onOk={onModalOk}
        onCancel={onModalCancel}
      >
        <div key="code" style={inputWithVerifyCodeStyle}>
          <Input name="code" />
          <VerifyCodeButton onClick={getCodeClick} />
        </div>
        <TreeSelect
          key="parentId"
          style={{ width: '100%' }}
          value={selectedParentId}
          dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
          placeholder="请选择上级菜单"
          fieldNames={treeFieldsName}
          onChange={onTreeChange}
          treeData={parentMenuList}
        />
      </PageModal>
    </>
  )
}

export default memo(MenuList)
